package com.topisv.tms.web.baseusers;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.BaseUsers;
import com.topisv.tms.entity.Task;
import com.topisv.tms.entity.User;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.baseusers.BaseUsersService;
import com.topisv.tms.service.task.TaskService;
import org.springside.modules.web.Servlets;

import com.google.common.collect.Maps;

/**
 * Task管理的Controller, 使用Restful风格的Urls:
 * 
 * List page     : GET /baseUsers/
 * Create page   : GET /baseUsers/create
 * Create action : POST /baseUsers/create
 * Update page   : GET /baseUsers/update/{id}
 * Update action : POST /baseUsers/update
 * Delete action : GET /baseUsers/delete/{id}
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/baseUsers")
public class BaseUsersController {

	private static final int PAGE_SIZE = 3;

	private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("account", "账号");
	}

	@Autowired
	private BaseUsersService baseUsersService;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long userId = getCurrentUserId();

		Page<BaseUsers> baseUsers = baseUsersService.getBaseUsers(userId, searchParams, pageNumber, PAGE_SIZE, sortType);
		model.addAttribute("baseUserss", baseUsers);
		model.addAttribute("sortType", sortType);
		model.addAttribute("sortTypes", sortTypes);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

		return "baseusers/baseUsersList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("baseUsers", new BaseUsers());
		model.addAttribute("action", "create");
		return "baseusers/baseUsersForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid BaseUsers baseUsers, RedirectAttributes redirectAttributes) {
		baseUsersService.saveBaseUsers(baseUsers);
		redirectAttributes.addFlashAttribute("message", "创建用户成功");
		return "redirect:/baseUsers/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("baseUsers", baseUsersService.getBaseUsers(id));
		model.addAttribute("action", "update");
		return "baseusers/baseUsersForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadBaseUsers") BaseUsers baseUsers, RedirectAttributes redirectAttributes) {
		baseUsersService.saveBaseUsers(baseUsers);
		redirectAttributes.addFlashAttribute("message", "更新用户成功");
		return "redirect:/baseUsers/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		baseUsersService.deleteBaseUsers(id);
		redirectAttributes.addFlashAttribute("message", "删除用户成功");
		return "redirect:/baseUsers/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadBaseUsers")
	public BaseUsers getBaseUsers(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return baseUsersService.getBaseUsers(id);
		}
		return null;
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
